/** 盘基本信息 */
const https = require('https'), fs = require("fs"), path = require('path');

let options = {
	hostname: 'api.aliyundrive.com',
	port: 443,
	path: '/',
	method: 'POST',
	headers: {
		'content-type': 'application/json;charset=UTF-8',
		'Origin': 'https://www.aliyundrive.com',
		'Referer': 'https://www.aliyundrive.com/',
		'X-Canary': 'client=web,app=adrive,version=v3.8.0',
		//'x-device-id': '2i7XGAcGqj8CAXVRuV7YF5Rp',
		//'x-signature': '9e99013a094bc2a35cacbb31772f084358e4142d82bc8ec24f726bf55606b63c126bd38b4af67d1f33411a7f7947a15af31008842ec66ab996125234166a551800',
		'Sec-Fetch-Dest': 'empty',
		'Sec-Fetch-Mode': 'cors',
		'Sec-Fetch-Site': 'same-site',
		'TE': 'trailers'
	}
};
let jsonmask = encodeURIComponent("next_marker,items(name,file_id,drive_id,type,size,created_at,updated_at,category,file_extension,parent_file_id,mime_type,starred,thumbnail,url,streams_info,content_hash,user_tags,user_meta,trashed,video_media_metadata,video_preview_metadata,sync_meta,sync_device_flag,sync_flag,punish_flag)");

let pathTree = {};

/** 获取文件列表 */
async function list(parent_file_id, cb, marker = ''){
	let cfg = require("./aliUser");
	if(typeof(cfg.expire_time) == 'string') cfg.expire_time = new Date(cfg.expire_time);
	//console.log(cfg.expire_time.getTime(), Date.now());
	if(Date.now() > cfg.expire_time.getTime()){
		await refresh();
		cfg = require("./aliUser");
	}

	options.path = "/adrive/v3/file/list?jsonmask=" + jsonmask;
	let sd ={"drive_id":cfg.default_drive_id,"parent_file_id":parent_file_id,"limit":100,"all":false,"url_expire_sec":1600,"image_thumbnail_process":"image/resize,w_400/format,jpeg","image_url_process":"image/resize,w_1920/format,jpeg","video_thumbnail_process":"video/snapshot,t_1000,f_jpg,ar_auto,w_300","fields":"*","order_by":"name","order_direction":"ASC"};
	if(marker) sd.marker = marker;
	sd = JSON.stringify(sd);
	options.headers['content-length'] = Buffer.byteLength(sd);
	options.headers['Authorization'] = cfg.token_type + ' ' + cfg.access_token;
	
	let req = https.request(options, (res)=>{
		let ret = Buffer.allocUnsafe(0)
		res.on('data', (chunk) => {
			ret = Buffer.concat([ret, chunk], ret.length + chunk.length);
		});
		res.on('end', () => {
			//console.log(ret.toString());
			let retItem = null
			try{
				retItem = JSON.parse(ret.toString());
			}catch(e){
				console.log(ret.toString());
			}
			if(cb){
				cb(retItem);
			}else if(retItem.items){
				for(let p of retItem.items){
					console.log((p.type=='folder'?'D':'F') + ' ' + p.name + ' ' + (p.size|0));
				}
			}else{
				console.log("list", ret.toString());
			}
		});
	});
	req.end(sd);
}
/** 刷新access_token  */
function refresh(){
	const cfg = require("./aliUser");
	options.path = "/token/refresh";
	let sd = JSON.stringify({"refresh_token":cfg.refresh_token});
	options.headers['content-length'] = Buffer.byteLength(sd);
	delete options.headers['Authorization'];

	return new Promise(function(resolve,reject){
		let req = https.request(options, (res)=>{
			let ret = Buffer.allocUnsafe(0)
			res.on('data', (chunk) => {
				ret = Buffer.concat([ret, chunk], ret.length + chunk.length);
			});
			res.on('end', () => {
				fs.writeFile("./aliUser.json", ret, ()=>{
					delete require.cache[__dirname + path.sep + "aliUser.json"];
					resolve();
				});
				//console.log("refresh", ret.toString());
			});
		});
		req.end(sd);		
	});

}

/** 获取完整目录 */
function getPath(pathstr){
	//console.log('获取完整目录', pathstr);
	let pathArr = pathstr.split("/"), index = 0, cpathtree = pathTree;
	return new Promise(function(resolve,reject){
		function cbpath(ret){
			//console.log(pathArr, index, cpathtree, ret)
			//缓存目录信息
			for(let p of ret.items){
				if(p.type == 'folder'){
					cpathtree.childs[p.name] = {file_id:p.file_id, type:p.type, childs:null}; //未获取过设置为空
				}else{
					cpathtree.childs[p.name] = {file_id:p.file_id, type:p.type, size:p.size};
				}
			}
			//是否有下一页文件信息
			if(ret.next_marker){
				setTimeout(()=>{
					list(cpathtree.file_id, cbpath, ret.next_marker);
				}, 5000);
				return;
			}
			//检查下一层目录
			//console.log('path', pathArr[index]);
			index++;
			if(index >= pathArr.length){
				resolve(cpathtree);
				return;
			}
			if(pathArr[index] in cpathtree.childs){
				cpathtree = cpathtree.childs[pathArr[index]];
				if(cpathtree.type == 'folder'){ //只有文件夹未获取过才需要重新获取
					if(!cpathtree.childs){ //未获取过才需要重新获取
						cpathtree.childs = {};
						setTimeout(()=>{
							list(cpathtree.file_id, cbpath)
						}, 5000);
					}else{ //已经请求过了
						resolve(cpathtree);
					}
				}else{ //非文件夹直接返回
					resolve(cpathtree);
				}
			}else{
				resolve(null);
			}
		}
		if(cpathtree.file_id){
			for(;index<pathArr.length;++index){
				if(pathArr[index]){
					if(pathArr[index] in cpathtree.childs){
						cpathtree = cpathtree.childs[pathArr[index]];
						if(cpathtree.type == 'folder'){
							if(!cpathtree.childs){ //未获取过才需要重新获取
								cpathtree.childs = {};
								list(cpathtree.file_id, cbpath);
								break;
							}							
						}else{ //文件跟目录不匹配
							return resolve(null);
						}
					}else{
						return resolve(null);
					}
				}
			}
			if(index >= pathArr.length) resolve(cpathtree);
			//cb(null, cpathtree);
		}else{
			list('root', cbpath);
			cpathtree.file_id = 'root';
			cpathtree.childs = {};
		}	
	});

}

exports.list = list;
exports.getPath = getPath;

/** 测试代码 */
//list('root');
//list('6188b040f1e834b5905743749e0eab00f6be964a')

//(async function(){
//	let files = await getPath('/2022中级财管/D奥（文件夹内自动更新中）/00-学习方法指导-征鸿（1讲全）/视频');
//	console.log(files);
//	files = await getPath('/系统');
//	console.log(files);
//})();

